package com.chinasofti.project.service.product.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinasofti.project.dal.mapper.custom.BzBookProductMapperCustom;
import com.chinasofti.project.dal.mapper.custom.BzShoppingCartMapperCustom;
import com.chinasofti.project.dal.model.BzShoppingCart;
import com.chinasofti.project.dal.model.custom.BzProduct;
import com.chinasofti.project.service.product.ShopcartService;

@Service("shopcartService")
public class ShopcartServiceImpl implements ShopcartService {

	@Autowired
	private BzShoppingCartMapperCustom bzShoppingCartMapperCustom;

	@Autowired
	private BzBookProductMapperCustom bzBookProductMapperCustom;

	@Override
	public int deletShopcart(BzShoppingCart bzShoppingCart) {
		return bzShoppingCartMapperCustom.deleteByShoppingCart(bzShoppingCart);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.chinasofti.project.service.product.ShopcartService#addShopcart(com.
	 * chinasofti.project.dal.model.BzShoppingCart)
	 */
	@Override
	public int addShopcart(BzShoppingCart bzShoppingCart) {
		BzShoppingCart bf = bzShoppingCartMapperCustom.selectByShoppingCart(bzShoppingCart);
		if (bf != null) {
			bf.setScProductNum(bf.getScProductNum() + 1);
			bzShoppingCartMapperCustom.updateByPrimaryKey(bf);
		} else {
			if (bzShoppingCart.getScProductNum() == 0) {
				bzShoppingCart.setScProductNum(1);
			}
			bzShoppingCartMapperCustom.insertSelective(bzShoppingCart);
		}
		return bzShoppingCartMapperCustom.selectNumByUserId(bzShoppingCart.getUserId());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.chinasofti.project.service.product.ShopcartService#selectByUserId(
	 * int)
	 */
	@Override
	public List<BzProduct> selectByUserId(int userId) {
		List<BzShoppingCart> bzShoppingCart = bzShoppingCartMapperCustom.selectProductByuserId(userId);
		List<BzProduct> productDetails = new ArrayList<BzProduct>();
		for (BzShoppingCart bsc : bzShoppingCart) {
			BzProduct bp = bzBookProductMapperCustom.selectByProductId(bsc.getProductId());
			// 查询bzproductdetails 为其添加数据
			bp.setScProductNum(bsc.getScProductNum());
			// 将ProductDetails 放入list
			productDetails.add(bp);
		}
		return productDetails;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.chinasofti.project.service.product.ShopcartService#updateShoppcart(
	 * com.chinasofti.project.dal.model.BzShoppingCart)
	 */
	@Override
	public int updateShoppcart(BzShoppingCart bzShoppingCart) {
		return bzShoppingCartMapperCustom.updateByShopcart(bzShoppingCart);
	}

}
